package com.example.enya_app_upgrade

import androidx.annotation.NonNull
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.widget.Toast
import androidx.core.content.FileProvider
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import java.io.File
import android.util.Log
/** EnyaAppUpgradePlugin */
class EnyaAppUpgradePlugin: FlutterPlugin, MethodCallHandler {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private lateinit var channel : MethodChannel
  private lateinit var context: Context

  override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    context = flutterPluginBinding.applicationContext
    channel = MethodChannel(flutterPluginBinding.binaryMessenger, "enya_app_upgrade")
    channel.setMethodCallHandler(this)
  }

  override fun onMethodCall(call: MethodCall, result: Result) {
    when (call.method) {
            "getAppInfo" -> {
                getAppInfo(context, result)
            }

            "getApkDownloadPath" -> {
                val version = call.argument<String>("version")
                result.success(context.getExternalFilesDir("")?.absolutePath?.plus("/app_update_${version}.apk"))
            }

            "install" -> {
                val path = call.argument<String>("path")
                path?.also {
                    startInstall(context, it)
                }
            }

            else -> {
                result.notImplemented()
            }
        }
  }

  override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
  }



  /**
     * 获取app信息
     */
    private fun getAppInfo(context: Context, result: MethodChannel.Result) {
        context.also {
            val packageInfo = it.packageManager.getPackageInfo(it.packageName, 0)
            val map = HashMap<String, String>()
            map["packageName"] = packageInfo.packageName
            map["versionName"] = packageInfo.versionName
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                map["versionCode"] = "${packageInfo.longVersionCode}"
            } else {
                @Suppress("DEPRECATION")
                map["versionCode"] = "${packageInfo.versionCode}"
            }
            Log.d("EnyaAppUpgradePlugin", "getAppInfo: $map")
            result.success(map)
        }
    }


    /**
     * 安装app，android 7.0及以上和以下方式不同
     */
    private fun startInstall(context: Context, path: String) {
        val file = File(path)
        if (!file.exists()) {
            return
        }

        val intent = Intent(Intent.ACTION_VIEW)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //7.0及以上
            println("安装地址:$path")
            val contentUri =
                FileProvider.getUriForFile(context, "${context.packageName}.fileProvider", file)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive")
            context.startActivity(intent)
        } else {
            //7.0以下
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive")
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(intent)
        }
    }
}
